import { MainContext } from "@/src/providers/MainProvider";
import {
  Box,
  Button,
  IconButton,
  Image,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Tab,
  TabList,
  Tabs,
  Modal,
  ModalOverlay,
  ModalContent,
  Spinner,
  Text,
  Flex,
} from "@chakra-ui/react";
import { useContext, useState } from "react";
import { useTranslation } from "@/src/i18n";

function Header() {
  const { changeLanguage, i18n } = useTranslation("common");
  const {
    t,
    battery,
    chargeFlag,
    connectMode,
    connectedKeyboard,
    setProfileIndex,
    profileIndex,
    activeProfile,
    currentTab,
    setCurrentTab,
    isRecordingMacro,
  } = useContext(MainContext);

  // 添加loading状态
  const [isLoading, setIsLoading] = useState(false);
  const [loadingText, setLoadingText] = useState(t("300"));

  // 配置项数据
  const configItems = [
    { id: 0, name: "71", color: "#3B82F6" },
    { id: 1, name: "72", color: "#10B981" },
    { id: 2, name: "73", color: "#8B5CF6" },
    { id: 3, name: "74", color: "#EF4444" },
    { id: 4, name: "75", color: "#F59E0B" },
  ];

  // Tab页配置
  const tabItems = [
    { lang: "51", id: "kb-keyremap", name: "按键映射" },
    { lang: "52", id: "kb-light", name: "灯光设置" },
    { lang: "53", id: "macro", name: "宏设置" },
    { lang: "58", id: "kb-setting", name: "键盘设置" },
    { lang: "59", id: "kb-deviceinfo", name: "设备信息" },
  ];

  // 切换语言
  const switcLanguage = async (language: string) => {
    changeLanguage(language);
  };

  // 切换配置方案
  const handleConfigChange = async (index: number) => {
    try {
      setIsLoading(true);
      setLoadingText(t("301") + t(configItems[index].name));

      setProfileIndex(index);
      await activeProfile(index);

      setTimeout(() => {
        setIsLoading(false);
      }, 800);
    } catch (error) {
      console.error(t("303"), error);
      setIsLoading(false);
    }
  };

  // 处理Tab切换
  const handleTabChange = (index: number) => {
    if (isRecordingMacro) {
      return;
    }
    setCurrentTab(tabItems[index].id);
  };

  // 布局图标SVG
  const LayoutIcon = ({ color }: { color: string }) => (
    <Box mr={2}>
      <svg
        width="16"
        height="16"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          d="M4 5H11V12H4V5Z"
          stroke={color}
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
        <path
          d="M4 16H11V19H4V16Z"
          stroke={color}
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
        <path
          d="M15 5H20V9H15V5Z"
          stroke={color}
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
        <path
          d="M15 13H20V19H15V13Z"
          stroke={color}
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    </Box>
  );

  return (
    <>
      <style jsx global>{`
        .chakra-tabs__tab {
          margin: 0 16px !important;
          padding: 8px 16px !important;
          color: rgb(100, 116, 139) !important;
          font-weight: 500 !important;
          font-size: 14px !important;
          transition: all 0.3s ease !important;
          border-radius: 20px !important;
          background: transparent !important;
          border: 1px solid transparent !important;
          position: relative !important;
          overflow: visible !important;
        }
        .chakra-tabs__tab:hover {
          color: rgb(255, 140, 0) !important;
          background: rgba(255, 165, 0, 0.08) !important;
          border-color: rgba(255, 165, 0, 0.2) !important;
        }
        .chakra-tabs__tab[aria-selected="true"] {
          color: rgb(255, 140, 0) !important;
          background: linear-gradient(
            135deg,
            rgba(255, 140, 0, 0.1) 0%,
            rgba(255, 165, 0, 0.1) 100%
          ) !important;
          border-color: rgba(255, 165, 0, 0.3) !important;
          box-shadow: 0 2px 8px rgba(255, 165, 0, 0.15) !important;
        }
        .chakra-tabs__tab-list {
          border-bottom: none !important;
          gap: 0 !important;
        }
        .chakra-tabs__tab[data-disabled] {
          opacity: 0.5 !important;
          cursor: not-allowed !important;
          pointer-events: none !important;
          color: rgb(156, 163, 175) !important;
        }
        .chakra-tabs__tab[data-disabled]:hover {
          color: rgb(156, 163, 175) !important;
          background: transparent !important;
          border-color: transparent !important;
        }
      `}</style>

      <Box
        position="sticky"
        top={0}
        zIndex={1000}
        style={{
          background: "rgba(255, 255, 255, 0.6)",
          backdropFilter: "blur(20px)",
          WebkitBackdropFilter: "blur(20px)",
          borderBottom: "1px solid rgba(255, 165, 0, 0.2)",
          boxShadow: "0 2px 12px rgba(255, 165, 0, 0.08)",
        }}
      >
        <Box
          height="64px"
          display="flex"
          alignItems="center"
          justifyContent="space-between"
          px={6}
        >
          {/* 左侧信息区域 */}
          <Flex align="center" gap={4} w="320px">
            <Text fontSize="sm" fontWeight="500" color="rgb(71, 85, 105)">
              {t("61") + connectMode}
            </Text>
            {/* <Text fontSize="sm" color="rgb(156, 163, 175)">
              |
            </Text>
            <Text fontSize="sm" fontWeight="500" color="rgb(71, 85, 105)">
              {chargeFlag == 1 ? t("63") : t("62")}
            </Text> */}

            {/* 电池图标 */}
            {/* <Flex align="center" gap={2}>
              <Box position="relative" w="32px" h="18px"> */}
                {/* 电池外框 */}
                {/* <Box
                  position="absolute"
                  top="0"
                  left="0"
                  w="28px"
                  h="18px"
                  border="2px solid"
                  borderColor="rgb(71, 85, 105)"
                  borderRadius="3px"
                  bg="rgba(255, 255, 255, 0.9)"
                /> */}
                {/* 电池电量 */}
                {/* <Box
                  position="absolute"
                  top="2px"
                  left="2px"
                  w={`${(battery / 100) * 24}px`}
                  h="14px"
                  bg={
                    battery > 30
                      ? "rgb(34, 197, 94)"
                      : battery > 15
                      ? "rgb(251, 191, 36)"
                      : "rgb(239, 68, 68)"
                  }
                  borderRadius="1px"
                  transition="all 0.3s ease"
                /> */}
                {/* 电池正极 */}
                {/* <Box
                  position="absolute"
                  top="6px"
                  right="-4px"
                  w="2px"
                  h="6px"
                  bg="rgb(71, 85, 105)"
                  borderRadius="0 2px 2px 0"
                /> */}
                {/* 充电图标 */}
                {/* {chargeFlag === 1 && (
                  <Box
                    position="absolute"
                    top="50%"
                    left="50%"
                    transform="translate(-50%, -50%)"
                    w="12px"
                    h="12px"
                    color="rgb(251, 191, 36)"
                  >
                    <svg viewBox="0 0 24 24" fill="currentColor">
                      <path d="M13 4L7 13H12L11 20L17 11H12L13 4Z" />
                    </svg>
                  </Box>
                )}
              </Box>
              <Text fontSize="sm" fontWeight="500" color="rgb(71, 85, 105)">
                {battery}%
              </Text>
            </Flex> */}
          </Flex>

          {/* 中间 Tab 导航 */}
          <Box flex="1" display="flex" justifyContent="center">
            <Tabs
              variant="unstyled"
              index={tabItems.findIndex((tab) => tab.id === currentTab)}
              onChange={handleTabChange}
            >
              <TabList>
                {tabItems.map((tab, index) => (
                  <Tab
                    key={tab.id}
                    isDisabled={isRecordingMacro}
                    data-disabled={isRecordingMacro ? "true" : undefined}
                  >
                    {t(tab.lang)}
                  </Tab>
                ))}
              </TabList>
            </Tabs>
          </Box>

          {/* 右侧菜单区域 */}
          <Flex align="center" gap={3} w="320px" justify="flex-end">
            {/* 配置下拉菜单 */}
            <Menu>
              <MenuButton
                as={Button}
                leftIcon={<LayoutIcon color="rgb(71, 85, 105)" />}
                variant="ghost"
                size="sm"
                color="rgb(71, 85, 105)"
                fontWeight="500"
                _hover={{
                  bg: "rgba(255, 165, 0, 0.08)",
                  color: "rgb(255, 140, 0)",
                }}
                _active={{
                  bg: "rgba(255, 165, 0, 0.1)",
                }}
                borderRadius="12px"
                px={3}
                style={{
                  transition: "all 0.3s ease",
                }}
              >
                {t(configItems[profileIndex]?.name || "71")}
              </MenuButton>
              <MenuList
                bg="rgba(255, 255, 255, 0.9)"
                backdropFilter="blur(20px)"
                border="1px solid rgba(255, 165, 0, 0.2)"
                borderRadius="12px"
                boxShadow="0 8px 24px rgba(255, 165, 0, 0.1)"
                p={2}
                minW="auto"
                style={{
                  WebkitBackdropFilter: "blur(20px)",
                }}
              >
                {configItems.map((item) => (
                  <MenuItem
                    key={item.id}
                    onClick={() => handleConfigChange(item.id)}
                    fontSize="sm"
                    color="rgb(71, 85, 105)"
                    borderRadius="8px"
                    py={2}
                    px={3}
                    _hover={{
                      bg: "rgba(255, 165, 0, 0.1)",
                      color: "rgb(255, 140, 0)",
                      transform: "translateX(2px)",
                    }}
                    bg={
                      profileIndex === item.id
                        ? "linear-gradient(135deg, rgba(255, 140, 0, 0.1) 0%, rgba(255, 165, 0, 0.1) 100%)"
                        : "transparent"
                    }
                    style={{
                      transition: "all 0.3s ease",
                    }}
                  >
                    <Flex align="center">
                      <LayoutIcon
                        color={
                          profileIndex === item.id
                            ? "rgb(255, 140, 0)"
                            : item.color
                        }
                      />
                      {t(item.name)}
                    </Flex>
                  </MenuItem>
                ))}
              </MenuList>
            </Menu>

            {/* 语言切换菜单 */}
            <Menu>
              <MenuButton
                as={IconButton}
                icon={
                  <Box position="relative" w="20px" h="20px">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                      <circle
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="rgb(71, 85, 105)"
                        strokeWidth="1.5"
                      />
                      <path
                        d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"
                        stroke="rgb(71, 85, 105)"
                        strokeWidth="1.5"
                      />
                    </svg>
                    <Text
                      position="absolute"
                      top="50%"
                      left="50%"
                      transform="translate(-50%, -50%)"
                      fontSize="8px"
                      fontWeight="bold"
                      style={{
                        background:
                          "linear-gradient(135deg, rgb(255, 140, 0) 0%, rgb(255, 165, 0) 100%)",
                        WebkitBackgroundClip: "text",
                        WebkitTextFillColor: "transparent",
                        backgroundClip: "text",
                      }}
                    >
                      {i18n.language === "cn" ? "中" : "EN"}
                    </Text>
                  </Box>
                }
                variant="ghost"
                size="sm"
                color="rgb(71, 85, 105)"
                _hover={{
                  bg: "rgba(255, 165, 0, 0.08)",
                  color: "rgb(255, 140, 0)",
                  transform: "translateY(-1px)",
                }}
                _active={{
                  bg: "rgba(255, 165, 0, 0.1)",
                  transform: "translateY(0)",
                }}
                borderRadius="12px"
                style={{
                  transition: "all 0.3s ease",
                }}
              />
              <MenuList
                bg="rgba(255, 255, 255, 0.9)"
                backdropFilter="blur(20px)"
                border="1px solid rgba(255, 165, 0, 0.2)"
                borderRadius="12px"
                boxShadow="0 8px 24px rgba(255, 165, 0, 0.1)"
                p={2}
                minW="auto"
                style={{
                  WebkitBackdropFilter: "blur(20px)",
                }}
              >
                <MenuItem
                  onClick={() => switcLanguage("cn")}
                  fontSize="sm"
                  color="rgb(71, 85, 105)"
                  borderRadius="8px"
                  py={2}
                  px={3}
                  _hover={{
                    bg: "rgba(255, 165, 0, 0.1)",
                    color: "rgb(255, 140, 0)",
                    transform: "translateX(2px)",
                  }}
                  style={{
                    transition: "all 0.3s ease",
                  }}
                >
                  中文
                </MenuItem>
                <MenuItem
                  onClick={() => switcLanguage("en")}
                  fontSize="sm"
                  color="rgb(71, 85, 105)"
                  borderRadius="8px"
                  py={2}
                  px={3}
                  _hover={{
                    bg: "rgba(255, 165, 0, 0.1)",
                    color: "rgb(255, 140, 0)",
                    transform: "translateX(2px)",
                  }}
                  style={{
                    transition: "all 0.3s ease",
                  }}
                >
                  English
                </MenuItem>
              </MenuList>
            </Menu>
          </Flex>
        </Box>
      </Box>

      {/* Loading Modal */}
      {isLoading && (
        <Modal isOpen={true} onClose={() => {}} isCentered>
          <ModalOverlay bg="rgba(0, 0, 0, 0.1)" backdropFilter="blur(8px)" />
          <ModalContent
            bg="rgba(255, 255, 255, 0.95)"
            backdropFilter="blur(20px)"
            borderRadius="20px"
            p={8}
            maxW="320px"
            border="1px solid rgba(255, 165, 0, 0.2)"
            boxShadow="0 8px 32px rgba(255, 165, 0, 0.1)"
            style={{
              WebkitBackdropFilter: "blur(20px)",
            }}
          >
            <Flex direction="column" align="center" justify="center">
              <Box mb={6} position="relative">
                <Spinner
                  size="xl"
                  thickness="3px"
                  speed="0.8s"
                  style={{
                    color: "rgb(255, 140, 0)",
                    filter: "drop-shadow(0 2px 4px rgba(255, 165, 0, 0.2))",
                  }}
                />
              </Box>
              <Text
                fontSize="md"
                fontWeight="500"
                textAlign="center"
                color="rgb(71, 85, 105)"
              >
                {loadingText}
              </Text>
            </Flex>
          </ModalContent>
        </Modal>
      )}
    </>
  );
}

export default Header;
